// composables/useImagePreview.js
import { ref } from 'vue';

export function useImagePreview() {
  const previewImage = (list, index = 0) => {
    if (!Array.isArray(list) || list.length === 0) return;

    uni.previewImage({
      current: list[index],
      urls: list,
      longPressActions: {
        itemList: ['保存图片'],
        success: function (res) {
          const selectedImg = list[res.index];
          saveImage(selectedImg);
        },
        fail: function (err) {
          console.error('长按操作失败', err);
        },
      },
    });
  };

  const saveImage = (imgUrl) => {
    checkAlbumPermission().then(() => {
      uni.getImageInfo({
        src: imgUrl,
        success(image) {
          uni.saveImageToPhotosAlbum({
            filePath: image.path,
            success: () => {
              uni.showToast({ title: '图片保存成功', icon: 'none' });
            },
            fail: (err) => {
              console.error('保存失败', err);
              uni.showToast({ title: '保存失败', icon: 'none' });
            },
          });
        },
        fail(err) {
          console.error('获取图片信息失败', err);
        },
      });
    }).catch((err) => {
      console.warn('用户拒绝相册权限', err);
      uni.showToast({ title: '需要相册权限才能保存图片', icon: 'none' });
    });
  };

  const checkAlbumPermission = () => {
    return new Promise((resolve, reject) => {
      // #ifdef MP-WEIXIN
      uni.getSetting({
        success(setting) {
          if (setting.authSetting['scope.writePhotosAlbum'] === false) {
            uni.showModal({
              title: '提示',
              content: '需要开启相册权限才能保存图片',
              success: res => {
                if (res.confirm) {
                  uni.openSetting();
                }
                reject();
              }
            });
          } else if (setting.authSetting['scope.writePhotosAlbum']) {
            resolve();
          } else {
            uni.authorize({
              scope: 'scope.writePhotosAlbum',
              success: resolve,
              fail: reject
            });
          }
        }
      });
      // #endif

      // #ifndef MP-WEIXIN
      // 非小程序平台不做权限检查
      resolve();
      // #endif
    });
  };

  return {
    previewImage
  };
}
